<template>
  <canvas
    id="canvas"
    ref="canvas"
    @mousedown="mousedown"
    @mouseover="mouseover"
    @mouseout="mouseout"
    style="box-shadow: 0 5px 10px green"
    width="0"
    height="0"
  ></canvas>
</template>

<script>
export default {
  name: "bg-canvas",
  props: ["src"],
  data() {
    return {
      ctx: null,
      canvas: null,
      image: new Image(),
      flag: false,
    };
  },
  mounted() {
    let { canvas } = this.$refs;
    this.canvas = this.$refs.canvas;
    this.ctx = this.canvas.getContext("2d");
  },
  methods: {
    mousedown(event) {
      if (this.flag) {
        let disX = event.clientX - this.canvas.offsetLeft;
        let disY = event.clientY - this.canvas.offsetTop;

        document.onmousemove = (ev) => {
          let l = ev.clientX - disX;
          let t = ev.clientY - disY;
          this.canvas.style.left = l + "px";
          this.canvas.style.top = t + "px";
        };
        document.onmouseup = () => {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      }
    },
    mouseover(event) {
      document.onkeydown = (event) => {
        if (event.keyCode === 32) {
          this.canvas.style.cursor = "move";
          this.flag = true;
        }
        event.preventDefault();
      };
      document.onkeyup = (event) => {
        if (event.keyCode === 32) {
          this.canvas.style.cursor = "default";
          this.flag = false;
        }
        event.preventDefault();
      };
      document.onmousewheel = (event) => {
        let down = true;
        // 兼容写法 detail -> 火狐
        down = event.wheelDelta ? event.wheelDelta < 0 : event.detail > 0;
        if (down) {
          // 向下
          this.canvas.width -= 10;
          this.canvas.height -= 10;
        } else {
          // 向上
          this.canvas.width += 10;
          this.canvas.height += 10;
        }
        this.ctx.drawImage(
          this.image,
          0,
          0,
          this.canvas.width,
          this.canvas.height
        );
        // event.preventDefault();
        // return false;
      };
    },
    mouseout(event) {
      document.onkeydown = null;
      document.onkeyup = null;
      console.log(document.onmousewheel);
      document.onmousewheel = null;
    },
  },
  watch: {
    src(newVal, oldVal) {
      this.image.onload = () => {
        this.canvas.width = this.image.width;
        this.canvas.height = this.image.height;
        this.ctx.drawImage(this.image, 0, 0);
      };

      this.image.src = this.src;
    },
  },
};
</script>
<style lang="less" scoped>
#canvas {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>